package com.bdqn.service.impl;

import com.bdqn.entity.AddressBook;
import com.bdqn.entity.OrderDetail;
import com.bdqn.entity.Orders;
import com.bdqn.entity.ShoppingCart;
import com.bdqn.mapper.*;
import com.bdqn.param.requset.OrderParam;
import com.bdqn.param.response.OrdersDto;
import com.bdqn.param.response.Page;
import com.bdqn.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author hunter
 * @since 2022-06-11
 */
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public Page<Orders> pageInfo(Integer page, Integer pageSize, OrderParam orderParam) {
        //进行分页
        PageHelper.startPage(page, pageSize);
        List<Orders> ordersList = ordersMapper.selectBY(orderParam);
        PageInfo<Orders> pageInfo = new PageInfo<Orders>(ordersList);
        //封装分页对象
        return new Page<Orders>(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 添加订单的操作
     *
     * @param orders
     * @param shoppingCarts
     * @return
     */
    @Override
    public int addOrder(Orders orders, List<ShoppingCart> shoppingCarts, HttpSession session) {
        try {
            Orders masterOrder = new Orders();
            masterOrder.setStatus(2); //订单状态
            //订单号 使用工具类随机生成6位数
            masterOrder.setNumber(ValidateCodeUtils.generateValidateCode(6));//订单号 --->随机生成
            masterOrder.setAddressBookId(orders.getAddressBookId());//地址id
            masterOrder.setPayMethod(orders.getPayMethod());
            masterOrder.setAmount(new BigDecimal(0));
            masterOrder.setRemark(orders.getRemark());
            masterOrder.setOrderTime(new Date(Constants.CREAT_ORDER_TIME));
            masterOrder.setCheckoutTime(new Date());//当前时间为订单支付时间
//        BigDecimal bigDecimal=new BigDecimal(0); //总金额
//        //获取购物车中的信息
//        for (ShoppingCart shoppingCart : shoppingCarts) {
//            bigDecimal.add(shoppingCart.getAmount()); //支付金额
//        }
            //为订单添加用户id
            masterOrder.setUserId(userMapper.selectByPhone(session.getAttribute(Constants.LOGIN_SESSION).toString()).getId());

            //通过地址id 拿到地址对象信息
            AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
            masterOrder.setPhone(addressBook.getPhone());
            masterOrder.setAddress(addressBook.getDetail());
            //获取user对象中的name
            masterOrder.setUserName(userMapper.selectByPhone(session.getAttribute(Constants.LOGIN_SESSION).toString()).getName());
            masterOrder.setConsignee(addressBook.getConsignee());

//      =============================添加一条主订单=======================================
            int insert = ordersMapper.insert(masterOrder);
            log.info("执行添加主订单的影响行数为: {}", insert);
            if (insert > 0) {
                System.out.println("=======添加主订单完成======");
            }
//      ===============================添加子订单=========================================

            System.out.println("此次添加子订单的个数为" + shoppingCarts.size());
            BigDecimal bigDecimal = new BigDecimal(0);
            int sumNum = 0;
            for (ShoppingCart shoppingCart : shoppingCarts) {
                //获取每个购物对象
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setName(shoppingCart.getName());
                orderDetail.setImage(shoppingCart.getImage());
                orderDetail.setNumber(shoppingCart.getNumber());
                orderDetail.setAmount(shoppingCart.getAmount());
                orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
                orderDetail.setDishId(shoppingCart.getDishId());
                orderDetail.setSetmealId(shoppingCart.getSetmealId());
                orderDetail.setOrderId(masterOrder.getId());//绑定主订单
                orderDetailMapper.insert(orderDetail);//添加子订单
                bigDecimal = bigDecimal.add(shoppingCart.getAmount().multiply(BigDecimal.valueOf(shoppingCart.getNumber())));//假如是总金额
                sumNum += orderDetail.getNumber();
            }
            //更新一下总金额
            masterOrder.setAmount(bigDecimal);
            System.out.println(("计算主订单的总金额为: {}" + bigDecimal));
            ordersMapper.updateById(masterOrder);
            /**
             * 最后清空购物车   循环删除 / 使用id集合进行一并删除
             */
            for (ShoppingCart shoppingCart : shoppingCartMapper.selectList(null)) {
                shoppingCartMapper.deleteById(shoppingCart.getId());
            }
            return sumNum;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 客户端的订单分页查询   -->传递子订单的所有的购买数量(一次完整的交易)
     *
     * @param page
     * @param pageSize
     * @param sumNum
     * @return
     */
    @Override
    public Page<OrdersDto> userPageInfo(Integer page, Integer pageSize, int sumNum) {
        //进行分页
        PageHelper.startPage(page, pageSize);
        //查询出所有的订单
        List<Orders> ordersList = ordersMapper.selectList(null);
        List<OrdersDto> ordersDtolist = new ArrayList<>();
        for (Orders orders : ordersList) {
            OrdersDto ordersDto = new OrdersDto();
            //赋值订单中所有的购买数量   将A-->B
            BeanUtils.copyProperties(orders, ordersDto);
            ordersDto.setSumNum(sumNum);
            ordersDtolist.add(ordersDto);
        }
        PageInfo<OrdersDto> pageInfo = new PageInfo<OrdersDto>(ordersDtolist);
        //封装分页对象
        return new Page<OrdersDto>(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getList());
    }

}
